<template>
  <section id="stockList">
    <ul class="tab">
      <li
        v-for="(item,index) in selectList"
        :class="tabIndex == index ? 'active' : ''"
        @click="switchSelect(item,index)"
        :key="index"
      >
        <img src="../assets/image/unselected.png" width="13" height="13" v-if="item === '自选'">
        <img
          src="../assets/image/selected.png"
          width="13"
          height="13"
          v-if="item === '自选' && tabIndex === 0"
        >
        {{item}}
      </li>
    </ul>
    <div class="search">
      <input type="text" placeholder="请输入产品名称/股票代码/简拼" v-model="searchVal" maxlength="25" @input="reCreate">
      <img src="../assets/image/search.png" alt width="16" v-if="!searchVal">
      <img src="../assets/image/del.png" alt width="16" v-else @click="searchVal='';">
    </div>
    <section class="table">
      <div class="title">
        <div>名称代码</div>
        <div>现价格</div>
        <div>涨跌幅</div>
      </div>
      <div v-if="!searchVal" class="scroll_bar_out_container">
        <div class="scroll_bar_container" id="stock_container">
          <div
            class="contentList"
            :ref="'scroll0'+index"
            id="stock_shower"
            v-for="(token,index)  in tickeList"
            :key="index"
            v-if="index==tabIndex">
            <div v-for="(item,itemIndex)  in token.list">
              <div>
                <img
                  src="../assets/image/unselected.png"
                  width="13"
                  height="13"
                  v-show="item.is_chose==0"
                  @click="AlertSymbol(item,true)"
                >
                <img
                  src="../assets/image/selected.png"
                  width="13"
                  height="13"
                  v-show="item.is_chose==1||tabIndex==0"
                  @click="AlertSymbol(item,false)"
                >
                <a href="javascript:void(0);"  @click="goDetail(item.name,item.type+':'+item.code,item.all,item.type,item.code)">{{item.name}}</a>
                <div>
                  <span>{{item.type == 'SSE' ? 'SH' : 'US'}}</span>
                  <span>{{item.code}}</span>
                </div>
              </div>
              <div>{{item.new_price?item.new_price:'--'}}</div>
              <div
                :class="{'red':Number(item.zhangdiefu)<0,'green':Number(item.zhangdiefu)>0}"
              >{{item.zhangdiefu ? (item.zhangdiefu>0?'+'+item.zhangdiefu:item.zhangdiefu) : '0.00'}}%</div>
            </div>
          </div>
        </div>
        <div class="scroll_bar_tool" id="stock_scroller">
          <div class="scroll_bar_up" id="stock_scroll_up"></div>
          <div class="scroll_bar_bar" id="stock_scroll_bar"></div>
          <div class="scroll_bar_down" id="stock_scroll_down"></div>
        </div>
      </div>

      <div class="search-content scroll_bar_out_container" v-if="searchVal" >
        <!--搜索状态-->
        <template v-if="dataList">
          <div class="scroll_bar_container" id="stock_container">
            <div id="stock_shower" class="contentList">
              <div v-for="(item,index) in dataList">
                <div class="first">
                  <a
                    href="javascript:void(0);"
                    @click="goDetail(item.name,item.type+':'+item.code,item.all,item.type,item.code)"
                    v-html="item.newsname"
                  ></a>
                  <div>
                    <span>{{item.type}}</span>
                    <span  v-html="item.newscode"></span>
                  </div>
                </div>
                <div>0.9985</div>
                <div class="green">-0.11%</div>
                <div class="add" v-if="item.is_chose==0" @click="AlertSymbol(item,true)"></div>
                <div class="del" v-else @click="AlertSymbol(item,false)"></div>
              </div>
            </div>
          </div>
          <div class="scroll_bar_tool" id="stock_scroller" v-if="!nodata">
            <div class="scroll_bar_up" id="stock_scroll_up"></div>
            <div class="scroll_bar_bar" id="stock_scroll_bar"></div>
            <div class="scroll_bar_down" id="stock_scroll_down"></div>
          </div>
        </template>
        <base-nodata v-if="nodata"></base-nodata>
      </div>
    </section>
  </section>
</template>
<script>
import {
  _getTickeList,
  _getTickePriceByList,
  _getUserTickeList,
  _addUserTicke,
  _deleteUserTicke,
  _ByListSearch
} from "@/axios/index.js";
import scrolls from '../util/scrollbar.js'
export default {
  data() {
    return {
      tabIndex: 1, // tab的index
      loadBox: [], //已经绑定了滚动事件的盒子
      selectList: ["自选", "上证", "纽交所", "纳斯达克"],
      searchVal: "", // 搜索值
      dataList: "", //搜索数据
      tickeList: ["", "", "", ""], //正常数据
      nodataListBol: [], //暂无数据
      params: [
        {},
        {
          type: "SSE", // 上海
          page: 1
        },
        {
          type: "NYSE", // 纽约
          page: 1
        },
        {
          type: "NASDAQ", // 美股
          page: 1
        }
      ],
      timer: "", //函数防抖回调
      nodata: false //搜索暂无数据
    };
  },
  watch: {
    searchVal() {
      var self = this;
      if (self.timer) {
        clearTimeout(self.timer);
      }
      self.timer = setTimeout(function() {
        self.search();
        self.timer = undefined;
      }, 400);
      var stock = new scrolls('stock');
    },
    tabIndex() {
      var _curIndex = this.tabIndex;
      if (!this.tickeList[_curIndex]) {
        this.getTickeList(this.params[_curIndex], "down");
      }
    },
    tickeList() {
      var stock = new scrolls('stock');
    }
  },
  computed: {
    user() {
      //是否登录
      var user = this.$store.state.user;
      return user;
    }
  },
  methods: {
    switchSelect(item, index) {
      let _self = this;
      if (_self.tabIndex != index) {
        _self.prevTabIndex = _self.tabIndex;
        _self.tabIndex = index;
      }
    },
    //添加自选
    async AlertSymbol(paramsItem, hangleBol) {
      let _self = this,
        res,
        _curIndex = _self.tabIndex,
        _bol = _self.tabIndex == 0,
        _sid = _bol ? paramsItem.stock_id : paramsItem.id;
      let para = {
        uid: _self.user.id,
        stock_id: _sid
      };

      if (hangleBol) {
        res = await _addUserTicke(para);
      } else {
        res = await _deleteUserTicke(para);
      }
      if (res.data.code === 200) {
        _self.$Message.success({
          content: hangleBol ? "添加成功" : "取消成功",
          duration: 1
        });
        var _curData = _self.tickeList[_curIndex].list;
        if (_bol) {
          for (var i = 0; i < _self.params.length; i++) {
            var _item = _self.params[i];
            if (_item.type == paramsItem.type) {
              if (_self.tickeList[i] && _self.tickeList[i].list.length) {
                for (var j = 0; j < _self.tickeList[i].list.length; j++) {
                  var _jItem = _self.tickeList[i].list[j];
                  if (_jItem.id == _sid) {
                    _self.$set(_jItem, "is_chose", hangleBol ? 1 : 0);
                    break;
                  }
                }
              }
              break;
            }
          }
        } else {
          _self.$set(paramsItem, "is_chose", hangleBol ? 1 : 0);
        }
        _self.alterUserList(
          _sid,
          hangleBol,
          JSON.parse(JSON.stringify(paramsItem))
        ); //修改自选
      } else {
        _self.$Message.error({
          content: res.data.msg,
          duration: 1
        });
      }
    },
    //本地添加取消 用户自选列表
    alterUserList(id, bol, item) {
      var _userData = this.tickeList[0] ? this.tickeList[0].list : "";
      if (_userData) {
        if (bol) {
          item.stock_id = item.id;
          _userData.unshift(item);
        } else {
          for (var i = 0; i < _userData.length; i++) {
            var _item = _userData[i];
            if (_item.stock_id == id) {
              _userData.splice(i, 1);
            }
          }
        }
      }
    },
    //获取股票列表
    async getTickeList(para, type) {
      const _self = this;
      let res,
        _bol = this.tabIndex == 0 ? true : false; //区别自选以及其他
      if (_bol) {
        res = await _getUserTickeList({ uid: _self.user.id }); //自选
      } else {
        res = await _getTickeList(para); //其他
      }
      if (res.data.code == 200) {
        _self.getTickePriceByList(
          _bol ? { list: res.data.data } : res.data.data,
          type
        );
      }
    },
    //获取股票详细数据
    async getTickePriceByList(ticke, type) {
      const _self = this;
      let list = "",
        tickeList = ticke.list,
        tL = tickeList.length,
        tIndex = _self.tabIndex,
        _bol = tIndex == 0 ? true : false,
        _typeData;

      if (tL == 0) return;
      for (var i = 0; i < tL; i++) {
        list += tickeList[i].market_code + ",";
      }
      const res = await _getTickePriceByList(list);

      //初次进入页面默认图表插件与头部信息显示数据 ： 保存类型 -- 保存第一条数据 
      let dataType={};

      for (var i = 0; i < tL; i++) {
        let _iItem = tickeList[i],
          _type = _iItem.type;
        _typeData = _self.getTypeData(_type);

        this.$set(
          _iItem,
          "new_price",
          res.data.split(";")[i].split(",")[_typeData.newPriceIndex]
        );
         this.$set(
          _iItem,
          "all",
          res.data.split(";")[i]
        );
        this.$set(
          _iItem,
          "zhangdiefu",
          _type == _self.params[1].type
            ? (
                ((res.data.split(";")[i].split(",")[_typeData.newPriceIndex] -
                  res.data.split(";")[i].split(",")[
                    _typeData.yesterdayPriceIndex
                  ]) /
                  res.data.split(";")[i].split(",")[_typeData.newPriceIndex]) *
                100
              ).toFixed(2)
            : res.data.split(";")[i].split(",")[_typeData.zhangdiefuIndex]
        );
         
         if(i==0) {
            dataType['type']=_iItem.type;
            dataType['all']=_iItem.all;
            dataType['code']=_iItem.code;
            dataType['name']=_iItem.name;
         }  
      }
      // 刚进页面时的第一条数据的详情，共享K给图表插件和头部信息的数据
      let $sotre=this.$store.state;
      if(!$sotre.stockList && !$sotre.stockSymBol){
        $sotre.stockSymBol=dataType['type'] +':' + dataType['code']
        this.disposeData(dataType.name,dataType.all,dataType.type,dataType.code)
      }

      if (type == "up") {
        ticke.list = _self.tickeList[tIndex].list.concat(tickeList);
      }
      _self.$set(_self.tickeList, tIndex, ticke);
      _self.$set(_self.nodataListBol, tIndex, !_self.tickeList[tIndex].pages);
      if (type != "up") {
        _self.$nextTick(() => {
          _self.scrollLoad();
        });
      }
    },
    //根据类型获取数据
    getTypeData(type) {
      let newPriceIndex, // 最新价下标
        yesterdayPriceIndex, // 昨日收盘价下标
        zhangdiefuIndex; // 涨跌幅下标
      switch (type) {
        case "NASDAQ":
          newPriceIndex = 1;
          zhangdiefuIndex = 2;
          break;
        case "NYSE":
          newPriceIndex = 1;
          zhangdiefuIndex = 2;
          break;
        case "SSE":
          newPriceIndex = 3;
          yesterdayPriceIndex = 2;
          break;
      }
      return {
        newPriceIndex,
        yesterdayPriceIndex,
        zhangdiefuIndex
      };
    },
    //搜索
    async search() {
      let self = this;
      let res = await _ByListSearch({
        keywords: self.searchVal
      });
      if (res.data.code === 200) {
        self.dataList = res.data.data;
        for (var i = 0; i < self.dataList.length; i++) {
          var item = self.dataList[i];
          var nameIndex = item.name
            .toLowerCase()
            .indexOf(self.searchVal.toLowerCase());
          var codeIndex = item.code
            .toLowerCase()
            .indexOf(self.searchVal.toLowerCase());
          if (nameIndex != -1) {
            var maxEnd = nameIndex + self.searchVal.length;
            var start = item.name.substring(0, nameIndex);
            var center =
              "<em class='red'>" +
              item.name.substring(nameIndex, maxEnd) +
              "</em>";
            var end = item.name.substring(maxEnd);
            var max = start + center + end;

            self.$set(item, "newsname", max);
          } else {
            self.$set(item, "newsname", item.name);
          }
          if (codeIndex != -1) {
            var maxEnd = codeIndex + self.searchVal.length;
            var start = item.code.substring(0, codeIndex);
            var center =
              "<em class='red'>" +
              item.code.substring(codeIndex, maxEnd) +
              "</em>";
            var end = item.code.substring(maxEnd);
            var max = start + center + end;
            self.$set(item, "newscode", max);
          } else {
            self.$set(item, "newscode", item.code);
          }
        }

        self.nodata = false;
      } else {
        self.dataList = [];
        self.nodata = true;
        if (self.searchVal == "") {
          self.nodata = false;
        }
      }
    },
    //函数节流
    throttle(func, wait) {
      let timeout;
      return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
          timeout = setTimeout(() => {
            timeout = null;
            func.apply(context, args);
          }, wait);
        }
      };
    },
    //滚动加载
    scrollLoad() {
      var _self = this;
      var item = _self.$refs["scroll0" + _self.tabIndex][0];
      if (!_self.loadBox[_self.tabIndex]&&_self.tabIndex!=0) {
        item.onscroll = function(e) {
       
          e.preventDefault();
          if (this.scrollTop + item.offsetHeight >= item.scrollHeight) {
            _self.$set(
              _self.params[_self.tabIndex],
              "page",
              _self.params[_self.tabIndex].page + 1
            );
            _self.getTickeList(_self.params[_self.tabIndex], "up");
          }
        };
        _self.$set(_self.loadBox,_self.tabIndex,true)
      }
    },
    //共享信息给图表与头部。
    disposeData(name,all,type,code){
      let dispose=all.split('=');
      let data=dispose[1].split(',');
          data[0]=name;
      let item;
      switch(type){
        case 'SSE':
          item={'code':code,'name':data[0],'open':data[1],'close':data[2],'price':data[3],'height':data[4],'low':data[5],'suecNum':data[8],'allMoey':data[9]}
        break;
        case 'NYSE':
          item={'code':code,'name':data[0],'open':data[5],'close':data[26],'price':data[1],'height':data[6],'low':data[7],'zf':data[2],'suecNum':data[10],'allMoey':null}
        break;
        case 'NASDAQ':
          item={'code':code,'name':data[0],'open':data[5],'close':data[26],'price':data[1],'height':data[6],'low':data[7],'zf':data[2],'suecNum':data[10],'allMoey':null}
        break;
      }
      this.$store.state.stockList=item
    },
    //股票详情
    goDetail(name,tcode,all,type,code) {
      this.$store.state.stockSymBol=tcode
      this.disposeData(name,all,type,code)
    },
    reCreate() {
      if (this.dataList) {
        var stock = new scrolls('stock');
      }
    }
  },
  created() {
    this.getTickeList(this.params[this.tabIndex], "down");
  },
  mounted() {
    if (!this.searchVal) {
      var stock = new scrolls('stock');
    }
  },
  updated() {
    if (!this.searchVal) {
      var stock = new scrolls('stock');
    }
  }
};
</script>
